<template>
  <div class="reports-page">
    <div class="page-header">
      <h2>健康报告生成</h2>
      <p>为指定老人生成健康报告并下载</p>
    </div>
    <el-card>
      <el-form :inline="true" :model="form" class="report-form">
        <el-form-item label="选择老人">
          <el-select v-model="form.elderlyId" placeholder="请选择老人" style="width: 200px">
            <el-option
              v-for="elderly in elderlyList"
              :key="elderly.id"
              :label="elderly.name"
              :value="elderly.id"
            />
          </el-select>
          <el-button type="primary" @click="generateReport" :loading="loading">生成报告</el-button>
        </el-form-item>
      </el-form>
      <el-divider />
      <div class="report-container">
        <div v-if="loading" class="loading">
          <el-progress :percentage="progress" :status="progressStatus" />
          <p>报告生成中... {{ progress }}%</p>
        </div>
        
        <div v-if="errorMessage" class="error-message">
          <el-alert :title="errorMessage" type="error" show-icon />
        </div>
        
        <div v-if="streaming" class="report-content">
          <div class="streaming-content" v-html="formattedReportContent"></div>
          <el-button 
            type="primary" 
            @click="downloadReport"
            class="download-btn"
            :disabled="!reportComplete"
          >
            下载报告
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useElderlyStore } from '@/stores/elderly'
import { getElderlyById } from '@/api/elderlyInfo/elderlyInfo';
import { getALLMedicationDataById } from '@/api/medicationinfo/medicationinfo';
import { getALLCheckupDataById } from '@/api/health_checkup_dateinfo/health_checkup_datainfo';
import { marked } from 'marked';
const form = reactive({
  elderlyId: ''
})

const errorMessage = ref('');
const loading = ref(false);
const streaming = ref(false);
const reportComplete = ref(false);
const progress = ref(0);
const progressStatus = ref('');
const elderly = ref<any>({});
const medicationData = ref<any>([]);
const checkupData = ref<any>([]);
const reportContent = ref('');
const fullReportContent = ref('');

const elderlyStore = useElderlyStore()
const elderlyList = computed(() => elderlyStore.elderlyList)

const formattedReportContent = computed(() => {
  return marked(reportContent.value || '', { breaks: true });
});

async function runWorkflow() {
  
  const url = 'https://api.coze.cn/v1/workflow/stream_run';
  const data = {
    workflow_id: "7521652042332061736",
    parameters: {
      "elderly": elderly.value,
      "medicationData": medicationData.value,
      "checkupData": checkupData.value
    }
  };
console.log(JSON.stringify(data))
  try {
    loading.value = true;
    streaming.value = true;
    
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer pat_e5OZBzeiGr4JoqONuBgEnPhp0cCbcHdMRkFXhNIkaWKV5aadMIei1HzBrXX4E9R1',
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify(data)

    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    if (!response.body) {
      throw new Error('ReadableStream not supported in this browser.');
    }

    // 创建读取器来处理流式数据
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        reportComplete.value = true;
        progress.value = 100;
        progressStatus.value = 'success';
        break;
      }
      
      // 解码并处理数据块
      buffer += decoder.decode(value, { stream: true });
      
      // 处理可能的多条SSE消息
      const events = buffer.split('\n\n');
      buffer = events.pop() || ''; // 保留不完整的消息
      
      for (const event of events) {
        if (event.trim()) {
          processSSEEvent(event);
        }
      }
      
      // 更新进度
      if (progress.value < 90) {
        progress.value = Math.min(progress.value + 10, 90);
      }
    }
  } catch (error: any) {
    errorMessage.value = error.message || '报告生成失败';
    progressStatus.value = 'exception';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
}

function processSSEEvent(eventText: string) {
  let eventData = '';
  let eventType = '';
  
  const lines = eventText.split('\n');
  for (const line of lines) {
    if (line.startsWith('event:')) {
      eventType = line.substring(6).trim();
    } else if (line.startsWith('data:')) {
      eventData += line.substring(5).trim();
    }
  }
  
  if (!eventData) return;

  try {
    // 处理可能的多行数据
    const dataLines = eventData.split('\n');
    for (const dataLine of dataLines) {
      if (!dataLine.trim()) continue;
      
      try {
        const parsedData = JSON.parse(dataLine);
        
        if (eventType === 'Message' && parsedData.content) {
          reportContent.value += parsedData.content; // 追加而不是替换
          fullReportContent.value += parsedData.content;
        } else if (eventType === 'Done') {
          reportComplete.value = true;
          progress.value = 100;
          progressStatus.value = 'success';
        }
      } catch (e) {
        console.error('Error parsing data line:', dataLine, e);
      }
    }
  } catch (e) {
    console.error('Error processing SSE event:', e);
  }
}

const generateReport = async () => {
  if (!form.elderlyId) {
    ElMessage.warning('请完整选择老人');
    return;
  }
  
  // 重置状态
  loading.value = true;
  streaming.value = true;
  reportComplete.value = false;
  progress.value = 0;
  progressStatus.value = '';
  reportContent.value = '';
  fullReportContent.value = '';
  errorMessage.value = '';

  try {
    const response0 = await getElderlyById(form.elderlyId);
    const response1 = await getALLMedicationDataById(form.elderlyId);
    const response2 = await getALLCheckupDataById(form.elderlyId);
    
    medicationData.value = response1.data;
    checkupData.value = response2.data;
    elderly.value = response0.data;
    console.log(elderly.value);
    console.log(medicationData.value);
    console.log(checkupData.value);
    await runWorkflow();
  } catch (error) {
    errorMessage.value = '获取老人数据失败';
    loading.value = false;
    streaming.value = false;
    ElMessage.error(errorMessage.value);
  }
}

const downloadReport = () => {
  if (!reportComplete.value) return;
  
  // 创建Blob对象
  const blob = new Blob([fullReportContent.value], { type: 'text/markdown' });
  const url = URL.createObjectURL(blob);
  
  // 创建下载链接
  const a = document.createElement('a');
  a.href = url;
  a.download = `${elderly.value.name || '老人'}_健康报告_${new Date().toISOString().slice(0, 10)}.md`;
  document.body.appendChild(a);
  a.click();
  
  // 清理
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  
  ElMessage.success('报告下载开始');
}
</script>

<style scoped>
.reports-page {
  max-width: 900px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}
.streaming-content :deep() h1 {
  font-size: 1.8em;
  margin: 0.8em 0;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.3em;
}

.streaming-content :deep() h2 {
  font-size: 1.5em;
  margin: 0.6em 0;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.2em;
}

.streaming-content :deep() h3 {
  font-size: 1.2em;
  margin: 0.5em 0;
}

.streaming-content :deep() ul,
.streaming-content :deep() ol {
  padding-left: 2em;
  margin: 0.5em 0;
}

.streaming-content :deep() li {
  margin: 0.3em 0;
}

.streaming-content :deep() pre {
  background-color: #f6f8fa;
  padding: 1em;
  border-radius: 4px;
  overflow: auto;
}

.streaming-content :deep() code {
  font-family: monospace;
  background-color: rgba(175, 184, 193, 0.2);
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-size: 0.9em;
}

.streaming-content :deep() blockquote {
  border-left: 4px solid #dfe2e5;
  color: #6a737d;
  padding: 0 1em;
  margin: 0.5em 0;
}
.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.report-form {
  margin-bottom: 20px;
}

.report-container {
  min-height: 300px;
}

.loading {
  text-align: center;
  padding: 20px;
}

.error-message {
  margin-bottom: 20px;
}

.report-content {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.streaming-content {
  min-height: 200px;
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
  background-color: white;
  border: 1px solid #ddd;
  margin-bottom: 15px;
}

.streaming-content h2, .streaming-content h3 {
  margin: 15px 0 10px 0;
  color: #333;
}

.streaming-content strong {
  color: #409EFF;
}

.streaming-content li {
  margin-left: 20px;
  list-style-type: disc;
}

.download-btn {
  margin-top: 15px;
}
</style>